﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

public delegate void ReadDataComplectedEventHandler(byte[] data);

/// <summary>
/// AsyncWebRequest 的摘要说明
/// </summary>
public class AsyncWebRequest
{
    private Uri url;

    public event ReadDataComplectedEventHandler OnReadDataComplected;

    public AsyncWebRequest(string absoluteUrl)
    {
        url = new Uri(absoluteUrl);
    }

    protected void readDataCallback(IAsyncResult ar)
    {

        WebRequestState rs = ar.AsyncState as WebRequestState;
        int read = rs.OrginalStream.EndRead(ar);
        if (read > 0)
        {
            rs.ms.Write(rs.Buffer, 0, read);
            rs.OrginalStream.BeginRead(rs.Buffer, 0, WebRequestState.BufferSize, new AsyncCallback(readDataCallback), rs);
        }
        else
        {
            rs.OrginalStream.Close();
            rs.WebResponse.Close();
            if (OnReadDataComplected != null)
            {
                OnReadDataComplected(rs.ms.ToArray());
            }
        }

    }

    protected void responseCallback(IAsyncResult ar)
    {
        HttpWebRequest req = ar.AsyncState as HttpWebRequest;
        if (req == null)
            return;
        HttpWebResponse response = req.EndGetResponse(ar) as HttpWebResponse;
        if (response.StatusCode != HttpStatusCode.OK)
        {
            response.Close();
            return;
        }
        WebRequestState st = new WebRequestState();
        st.WebResponse = response;
        Stream repsonseStream = response.GetResponseStream();
        st.OrginalStream = repsonseStream;
        repsonseStream.BeginRead(st.Buffer, 0, WebRequestState.BufferSize, new AsyncCallback(readDataCallback), st);
    }

    public void BeginReuest(ReadDataComplectedEventHandler handler)
    {
        HttpWebRequest req = HttpWebRequest.Create(url.AbsoluteUri) as HttpWebRequest;
        req.BeginGetResponse(new AsyncCallback(responseCallback), req);
    }

}